package com.qianbao.service.address.impl;

import com.qianbao.components.excepion.CommonException;
import com.qianbao.components.excepion.ExceptionEnum;
import com.qianbao.components.uuid.SVUuidTool;
import com.qianbao.dao.address.AddressDao;
import com.qianbao.domain.address.AddressEntity;
import com.qianbao.service.address.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao dao;

    @Override
    public List<AddressEntity> findAllAddressList(String customId) throws CommonException{
        if (customId != null && customId.length() > 0){
            return dao.findAllAddressList(customId);
        }else {
            throw new CommonException(ExceptionEnum.Request_Params_Invalid.getCode(),
                    ExceptionEnum.Request_Params_Invalid.getMessage());
        }
    }

    @Override
    public void saveAddress(AddressEntity entity) throws CommonException {
        // 生成地址唯一标识
        entity.setAddress_id(SVUuidTool.getUUID());

        int rows = dao.saveAddress(entity);

        if (rows != 1){
            throw new CommonException(ExceptionEnum.Sql_insert_fail.getCode(),
                    ExceptionEnum.Sql_insert_fail.getMessage());
        }

    }

    @Override
    public void updateAddress(AddressEntity entity) throws CommonException {

        if (entity.getAddress_id() != null && entity.getAddress_id().length() > 0){
            int rows = dao.updateAddress(entity);
            if (rows != 1){
                throw new CommonException(ExceptionEnum.Sql_update_fail.getCode(),
                        ExceptionEnum.Sql_update_fail.getMessage());
            }
        }else {
            throw new CommonException(ExceptionEnum.Request_Params_Invalid.getCode(),
                    ExceptionEnum.Request_Params_Invalid.getMessage());
        }
    }

    @Override
    public void deleteAddress(String addressId) throws CommonException {

        if (addressId != null && addressId.length() > 0){
            int rows = dao.deleteUserAddress(addressId);
            if (rows != 1){
                throw new CommonException(ExceptionEnum.Sql_delete_fail.getCode(),
                        ExceptionEnum.Sql_delete_fail.getMessage());
            }
        }else {
            throw new CommonException(ExceptionEnum.Request_Params_Invalid.getCode(),
                    ExceptionEnum.Request_Params_Invalid.getMessage());
        }
    }

}
